package com.aaamvc.xml;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 解析XML配置文件
 * @author Administrator
 *
 */
public class XmlParser
{

	public static Map<String, ActionBean> getConfig() throws Exception
	{
		SAXReader reader = new SAXReader();
		InputStream in = XmlParser.class.getClassLoader().getResourceAsStream("aaamvc_config.xml");  
		Document doc = reader.read(in);  
		Element root = doc.getRootElement();  
		
		Map<String, ActionBean> beanMap = new HashMap<String, ActionBean>();
		
		for(Iterator iter = root.elementIterator(); iter.hasNext();)
		{
			Element e = (Element)iter.next();
			List<ResultBean> resultBeans = new ArrayList<ResultBean>();
			//封装XML文件result元素
			List resultList = e.elements();
			for (int i = 0; i < resultList.size(); i++) {
				Element resultElement = (Element)resultList.get(i);
				ResultBean resultBean = new ResultBean(resultElement.attributeValue("name"),
						resultElement.attributeValue("type"), 
						resultElement.getData().toString());
				resultBeans.add(resultBean);
			}
			//封装XML文件Action元素
			String actionName = e.attributeValue("name").split("_")[0];
			ActionBean actionBean = new ActionBean(actionName,e.attributeValue("class"), resultBeans);
			beanMap.put(actionName, actionBean);
		}
		return beanMap;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public static void writer() throws Exception
	{
		// Document document = DocumentHelper.createDocument();
		// Element root = DocumentHelper.createElement("student");
		// document.setRootElement(root);

		Element root = DocumentHelper.createElement("student");
		Document document = DocumentHelper.createDocument(root);

		root.addAttribute("name", "zhangsan");

		Element helloElement = root.addElement("hello");
		Element worldElement = root.addElement("world");

		helloElement.setText("hello");
		worldElement.setText("world");

		helloElement.addAttribute("age", "20");

		XMLWriter xmlWriter = new XMLWriter();
		xmlWriter.write(document);
		
		OutputFormat format = new OutputFormat("    ", true);
		
		XMLWriter xmlWriter2 = new XMLWriter(new FileOutputStream("student2.xml"), format);
		xmlWriter2.write(document);
		
		XMLWriter xmlWriter3 = new XMLWriter(new FileWriter("student3.xml"), format);
		xmlWriter3.write(document);
		xmlWriter3.close();

	}
}
